// pages/databaseGuide/databaseGuide.js

const app = getApp()

Page({
  
  data: {
    applyorgFlag: true
  },

  onLoad: function (options) {
    this.onGetOpenid();
    let that = this;

    if (!wx.cloud) {
      wx.redirectTo({
        url: '../chooseLib/chooseLib',
      })
      return
    }

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
              console.info("用户信息为：" + JSON.stringify(res.userInfo, null, 2));
              app.globalData.nickName = res.userInfo.nickName
              app.globalData.avatarUrl = res.userInfo.avatarUrl
              app.globalData.hignavatarUrl = app.globalData.avatarUrl.replace(/132/g, '0')
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                nickName: res.userInfo.nickName,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  
    var odata = JSON.parse(options.orgdata);
    console.log("进入详情页参数：" + odata)
    that.odata = odata
    console.log("odata title：" + odata.title)
    console.log("odata:" + JSON.stringify(odata, null, 2));
    this.setData({
      orgdatedetail: odata
    })
    const db = wx.cloud.database()
    db.collection('USERORG').where({
      _openid: app.globalData.openid,
      orgid: odata._id
    }).count({
      success: function (res) {
        console.log("查询用户是否加入群组" + res.total);
        that.data.totalcount = res.total;
        var f = that.data.totalcount > 0;
        console.log("查询用户是否加入群组" + f);
        if (that.data.totalcount > 0){
          that.setData({
            applyorgFlag: false
          })
        }
      }
    })
  },

  onShareAppMessage: function () {
    let that = this;
    console.log("报名参数：" + that.odata)
    var orgdata = JSON.stringify(that.odata);
    if (app.globalData.nickName == null) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }
    return {
      title: app.globalData.nickName + "邀请您加入" + that.odata.title + "一起打卡",
      imageUrl: that.odata.headurl,
      path: "/pages/orgdetail/orgdetail?orgdata=" + orgdata
    }
  },

  AppThisOrg: function (e) {
    if (app.globalData.nickName == null) {
      wx.navigateTo({
        url: '../login/login',
      })
      return;
    }

    var odata = e.currentTarget.dataset.id
    console.log("报名参数：" + e.currentTarget.dataset.id.title)
    console.log("列表跳转详情页参数中_id值为：" + e.currentTarget.dataset.id._id)
    var nickName = app.globalData.nickName;
    const db = wx.cloud.database()
    db.collection('USERORG').add({
      data: {
        nickName: nickName,
        orgid: odata._id,
        orgdata: odata
      },
      success: res => {
        wx.reLaunch({
          url: '../msg/msg_success',
        })
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
      },
      fail: err => {
        wx.reLaunch({
          url: '../msg/msg_fail',
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  },

  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        var _openid = res.result.openid
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  goHome: function() {
    const pages = getCurrentPages()
    if (pages.length === 2) {
      wx.navigateBack()
    } else if (pages.length === 1) {
      wx.redirectTo({
        url: '../index/index',
      })
    } else {
      wx.reLaunch({
        url: '../index/index',
      })
    }
  }
})